package com.cangsan.erhai.service.impl;

import com.cangsan.erhai.entity.SysUser;
import com.cangsan.erhai.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Objects;

@Service
public class MyUserServiceDetailsImpl implements UserDetailsService {
    @Autowired
    SysUserService userService;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
     SysUser user= userService.getByUserName(userName);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        return new User(user.getUserName(),user.getPassword(),getUserAutharity(user.getUserId()));
    }

    public Collection<? extends GrantedAuthority> getUserAutharity(Long userId) {
      String authority=  userService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
